<template>
  <div class="role-management-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <div class="header-right">
            <el-button type="primary" @click="handleAdd">新增角色</el-button>
          </div>
        </div>
      </template>

      <!-- 角色列表 -->
      <el-table
        v-loading="loading"
        :data="roleList"
        style="width: 100%"
        border
      >
        <el-table-column prop="name" label="角色名称" min-width="120" />
        <el-table-column prop="code" label="角色编码" min-width="120" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ new Date(row.createTime).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="primary" link @click="handlePermission(row)">
              权限设置
            </el-button>
            <el-button
              v-if="!row.isSystem"
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入角色编码" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限设置"
      width="600px"
    >
      <div class="permission-dialog-content">
        <!-- 搜索框 -->
        <div class="permission-search">
          <el-input
            v-model="permissionSearchKeyword"
            placeholder="搜索权限"
            clearable
            prefix-icon="Search"
          />
        </div>
        
        <!-- 操作按钮 -->
        <div class="permission-actions">
          <el-button @click="handlePermissionReset">重置</el-button>
          <el-checkbox
            v-model="checkAll"
            @change="handlePermissionCheckAll"
          >
            全选
          </el-checkbox>
        </div>

        <!-- 权限树 -->
        <div class="permission-tree">
          <el-tree
            ref="permissionTreeRef"
            :data="filteredPermissionTree"
            show-checkbox
            node-key="id"
            :props="{
              label: 'name',
              children: 'children'
            }"
            :default-checked-keys="checkedPermissions"
            highlight-current
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 加载状态
const loading = ref(false)

// 角色列表数据
const roleList = ref([
  {
    id: 1,
    name: '超级管理员',
    code: 'SUPER_ADMIN',
    description: '系统超级管理员，拥有所有权限',
    createTime: '2024-01-01T10:00:00Z',
    isSystem: true
  },
  {
    id: 2,
    name: '用户管理员',
    code: 'USER_ADMIN',
    description: '负责用户管理模块的管理员',
    createTime: '2024-01-01T11:00:00Z',
    isSystem: true
  },
  {
    id: 3,
    name: '商品管理员',
    code: 'PRODUCT_ADMIN',
    description: '负责商品管理模块的管理员',
    createTime: '2024-01-01T12:00:00Z',
    isSystem: true
  },
  {
    id: 4,
    name: '订单管理员',
    code: 'ORDER_ADMIN',
    description: '负责订单管理模块的管理员',
    createTime: '2024-01-01T13:00:00Z',
    isSystem: true
  },
  {
    id: 5,
    name: '商店管理员',
    code: 'STORE_ADMIN',
    description: '负责商店管理模块的管理员',
    createTime: '2024-01-01T14:00:00Z',
    isSystem: true
  },
  {
    id: 6,
    name: '商户',
    code: 'MERCHANT',
    description: '商户用户，可管理自己的商品、订单和数据',
    createTime: '2024-01-01T15:00:00Z',
    isSystem: true
  }
])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  name: '',
  code: '',
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '只能包含大写字母和下划线', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' }
  ]
}

// 角色权限预设
const rolePermissionPresets = {
  SUPER_ADMIN: [1, 11, 111, 112, 113, 114, 12, 121, 122, 123, 124, 125, 13, 131, 132, 133, 134, 2, 21, 211, 212, 213, 214, 215, 22, 221, 222, 223, 224, 3, 31, 311, 312, 313, 32, 321, 322, 4, 41, 411, 412, 42, 421, 422, 5, 51, 511, 512, 513, 514, 52, 521, 522],
  USER_ADMIN: [11, 111, 112, 113, 114],
  PRODUCT_ADMIN: [2, 21, 211, 212, 213, 214, 215, 22, 221, 222, 223, 224],
  ORDER_ADMIN: [3, 31, 311, 312, 313, 32, 321, 322],
  STORE_ADMIN: [5, 51, 511, 512, 513, 514, 52, 521, 522],
  MERCHANT: [2, 21, 211, 212, 213, 214, 3, 31, 311, 312, 4, 41, 411, 412]
}

// 权限树相关
const permissionDialogVisible = ref(false)
const permissionTreeRef = ref(null)
const currentRole = ref(null)
const checkedPermissions = ref([])
const permissionSearchKeyword = ref('')

// 过滤后的权限树
const filteredPermissionTree = computed(() => {
  if (!permissionSearchKeyword.value) {
    return permissionTree.value
  }
  
  const filterTree = (nodes) => {
    return nodes.filter(node => {
      const matchKeyword = node.name.toLowerCase().includes(permissionSearchKeyword.value.toLowerCase())
      if (node.children) {
        node.children = filterTree(node.children)
        return matchKeyword || node.children.length > 0
      }
      return matchKeyword
    })
  }
  
  return filterTree(JSON.parse(JSON.stringify(permissionTree.value)))
})

// 新增角色
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该角色吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟API调用
    setTimeout(() => {
      ElMessage.success('角色删除成功')
    }, 1000)
  })
}

// 打开权限设置
const handlePermission = (row) => {
  currentRole.value = row
  // 根据角色预设权限设置选中项
  checkedPermissions.value = rolePermissionPresets[row.code] || []
  permissionDialogVisible.value = true
}

// 提交角色表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success(dialogType.value === 'add' ? '角色添加成功' : '角色更新成功')
        dialogVisible.value = false
      }, 1000)
    }
  })
}

// 提交权限设置
const handlePermissionSubmit = () => {
  if (!permissionTreeRef.value) return
  
  const checkedKeys = permissionTreeRef.value.getCheckedKeys()
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
  const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]
  
  // 模拟API调用
  setTimeout(() => {
    ElMessage.success('权限设置成功')
    permissionDialogVisible.value = false
  }, 1000)
}

// 重置权限设置
const handlePermissionReset = () => {
  if (!permissionTreeRef.value || !currentRole.value) return
  
  // 根据角色预设权限重置选中项
  checkedPermissions.value = rolePermissionPresets[currentRole.value.code] || []
  permissionTreeRef.value.setCheckedKeys(checkedPermissions.value)
}

// 全选/取消全选
const handlePermissionCheckAll = (checked) => {
  if (!permissionTreeRef.value) return
  
  const allKeys = getAllPermissionKeys(permissionTree.value)
  permissionTreeRef.value.setCheckedKeys(checked ? allKeys : [])
}

// 获取所有权限ID
const getAllPermissionKeys = (nodes) => {
  const keys = []
  const traverse = (node) => {
    if (node.children) {
      node.children.forEach(traverse)
    } else {
      keys.push(node.id)
    }
  }
  nodes.forEach(traverse)
  return keys
}
</script>

<style scoped>
.role-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.permission-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.permission-search {
  width: 100%;
}

.permission-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.permission-tree {
  height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px;
}
</style> 